package com.woniuxy.java106crm.controller;

import com.woniuxy.java106crm.annotation.RequireMethod;
import com.woniuxy.java106crm.entity.LoginInfo;
import com.woniuxy.java106crm.entity.Perms;
import com.woniuxy.java106crm.entity.User;
import com.woniuxy.java106crm.handler.ValidatesException;
import com.woniuxy.java106crm.request.Message;
import com.woniuxy.java106crm.request.ResponseResult;
import com.woniuxy.java106crm.request.StateCode;
import com.woniuxy.java106crm.service.LoginInfoService;
import com.woniuxy.java106crm.service.UserService;
import com.woniuxy.java106crm.util.JWTUtil;
import com.woniuxy.java106crm.util.RandomUtils;
import com.woniuxy.java106crm.util.WebUtil;
import com.woniuxy.java106crm.vo.LoginVo;
import com.woniuxy.java106crm.vo.SelectUserVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Api(tags = "用户管理模块API文档")
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    //注入登录日志的服务层
    @Resource
    private LoginInfoService loginInfoService;


    //登录
    @PostMapping("/login")
    public ResponseResult login(@RequestBody LoginVo loginVo, HttpServletResponse response){
        log.debug(loginVo.toString());
        //登录
        User user = userService.login(loginVo);

        //将登录信息添加到登录日志中
        //1.获取信息
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setUsername(loginVo.getUsername());//获取用户姓名
        loginInfo.setLoginTime(RandomUtils.getCurrentDateForString());//获取登录时间
        loginInfo.setMethodName("login");//直接指定方法名
        loginInfo.setIp(WebUtil.getHttpServletRequest().getRemoteAddr());//获取IP地址
        loginInfo.setRequestType(WebUtil.getHttpServletRequest().getMethod());//获取请求方法
        loginInfo.setUrl(String.valueOf(WebUtil.getHttpServletRequest().getRequestURL()));//获取请求的URL
        //2.调用service方法
        log.debug(loginInfo.toString());
        loginInfoService.addLoginInfo(loginInfo);


        //假设登录成功 颁发令牌
        String token = JWTUtil.generateToken(user.getId(),user.getUsername());
        //普通数据通过return返回，token通过响应头返回
        response.setHeader("Authorization", token);
        //暴露头，告诉浏览器别过滤这个头，让前端程序能够拿到头
        response.setHeader("Access-Control-Expose-Headers","Authorization");
        //将token放入redis
        redisTemplate.opsForValue().set(token,"");
//        System.out.println(user);
        //封装菜单
        List<Perms> menu = userService.getMenu(user.getRoleList());
        //封装数据
        return new ResponseResult<>(StateCode.SUCCESS, Message.LOGIN_SUCCESS,menu);
    }
    //查询权限为客户经理的用户
    @GetMapping("/selectManager")
    public ResponseResult<List<SelectUserVo>>  selectManager(){
        return new ResponseResult<>(ResponseResult.OK,userService.selectManager());
    }
    //查询全部系统用户
    @RequireMethod("查询全部系统用户")
    @PostMapping("/queryUsers")
    public ResponseResult<List<User>>  queryUsers(@RequestBody User user){
        return new ResponseResult<>(ResponseResult.OK,userService.queryUsers(user));
    }

    //添加系统用户
    @RequireMethod("添加系统用户")
    @PostMapping("/add")
    public ResponseResult<Boolean> addUser(@Validated @RequestBody User user, BindingResult bindingResult){
        log.debug("{}",user);
        //判断是否有不满足校验条件的数据
        if(bindingResult.hasFieldErrors()){
            throw new ValidatesException(bindingResult.getFieldErrors().get(0).getDefaultMessage());
        }
        user.setPassword(new BCryptPasswordEncoder().encode("12345"));
        user.setStatus("1");
        return new ResponseResult<>(ResponseResult.OK,userService.addUser(user));
    }
    //编辑用户信息
    @RequireMethod("编辑用户信息")
    @PostMapping("/update")
    public ResponseResult<Boolean> updateUser(@RequestBody User user){
        return new ResponseResult<>(ResponseResult.OK,userService.updateUser(user));
    }
    //删除用户
    @RequireMethod("删除用户")
    @DeleteMapping("/delete/{id}")
    public ResponseResult<Boolean> deleteUser(@PathVariable("id") Integer id){
        return new ResponseResult<>(ResponseResult.OK,userService.deleteUser(id));
    }
    //批量删除用户
    @RequireMethod("批量删除用户")
    @DeleteMapping("/deleteUsers/{ids}")
    public ResponseResult deleteUsers(@PathVariable("ids")String ids){
        userService.deleteUsers(ids);
        return new ResponseResult<>(ResponseResult.OK,null);
    }
    //给用户分配角色
    @RequireMethod("给用户分配角色")
    @PutMapping("/assginRole/{uid}/{rids}")
    public ResponseResult assginRole(@PathVariable("uid") Integer uid,@PathVariable("rids") String rids){
        userService.assginRole(uid,rids);
        return new ResponseResult<>(ResponseResult.OK,null);
    }
}
